#include<iostream>
#include<signal.h>
#include<cstring>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>

using namespace std;

void handler(int signo)
{
    pid_t rid=waitpid(-1,nullptr,0);
    cout<<"I am process:"<<getpid()<<"catch a signo:"<<signo<<"child process quit:"<<rid<<endl;
}

int main()
{
    signal(17,handler);

    pid_t id=fork();
    if(id==0)
    {
        while(true)
        {
            cout<<"I am child process:"<<getpid()<<",ppid()"<<getppid()<<endl;
            sleep(1);
            break;
        }
        exit(0);
    }
    while(true)
    {
        cout<<"I am father process:"<<getpid()<<endl;
        sleep(1);
    }

    return 0;
}


#if 0
volatile int flag=0;

void handler(int signo)
{
    cout<<"catch a signal:"<<signo<<endl;
    flag=1;
}

int main()
{
    signal(2,handler);

    while(!flag);//flag 0  !flag 真
    
    cout<<"process quit normal"<<endl;
    return 0;
}
#endif 


#if 0
//打印位图
void PrintPending()
{
    sigset_t set;
    sigpending(&set);

    for(int signo=1;signo<=31;signo++)
    {
        if(sigismember(&set,signo)) cout<<"1";
        else cout<<"0";
    }
    cout<<"\n";
}

//信号的处理方法
void handler(int signo)
{
    cout<<"catch a signal,signal number:"<<signo<<endl;
    while(1)
    {
        PrintPending();
        sleep(1);
    }
}

int main()
{
    struct sigaction act,oact;
    memset(&act,0,sizeof(act));
    memset(&oact,0,sizeof(oact));

    act.sa_handler=handler;//设置信号的处理方法
    sigaction(2,&act,&oact);

    while(true)
    {
        cout<<"I am a process:"<<getpid()<<endl;
        sleep(1);
    }

    return 0;
}
#endif 